#include "StdAfx.h"
#include "SpinUnits.h"
#include "NumSpinCtrl.h"

using namespace std;
using namespace nsEnumsUn;

double nsUnitUtils::computeUnitFactor( EUNIT Unit, size_t nDPI )
{
	double nUnitFactor = 0.0;

	if ( nDPI != 0 )
	{
		switch( Unit )
		{
		case eunPixel:
			nUnitFactor = 1.0;
			break;

		case eunCm:
			nUnitFactor = 2.54 / nDPI;
			break;

		case eunInch:
			nUnitFactor = 1.0 / nDPI;
		}
	}

	return nUnitFactor;
}



CSpinUnits::CSpinUnits()
{
	CurrentUnit_ = eunNone;
	nPixelToUnitFactor_ = 0;
	nDPI_ = 0;
}

CSpinUnits::~CSpinUnits()
{
}

void CSpinUnits::addSpinControl( CNumSpinCtrl &SpinControl, const int nPixelMin, const int nPixelMax )
{
	SSpin Spin;
	Spin.pSpinControl = &SpinControl;
	Spin.nPixelMin = nPixelMin;
	Spin.nPixelMax = nPixelMax;
//	vSpin_.push_back( Spin );

	size_t iAddedControl = vSpin_.size() - 1;
	setControlRanges( iAddedControl, iAddedControl );
}

void CSpinUnits::setUnit( EUNIT Unit )
{
	CurrentUnit_ = Unit;
	nPixelToUnitFactor_ = nsUnitUtils::computeUnitFactor( CurrentUnit_, nDPI_ ),

	setControlRanges( 0, vSpin_.size() - 1 );
}

void CSpinUnits::setDPI( int nDPI )
{
	nDPI_ = nDPI;

	nPixelToUnitFactor_ = nsUnitUtils::computeUnitFactor( CurrentUnit_, nDPI_ ),

		setControlRanges( 0, vSpin_.size() - 1 );
}


void CSpinUnits::setControlRanges( size_t iStart, size_t iEnd )
{
	if ( vSpin_.size() == 0 ) return;

	float nDelta = CurrentUnit_ == eunPixel ? 1.f :
		CurrentUnit_ == eunCm ? 0.01f :
		CurrentUnit_ == eunInch ? 0.01f : 0.f;

	// change ranges of all controls
	vector<SSpin>::iterator it = vSpin_.begin() + iStart,
							end = vSpin_.begin() + iEnd + 1;
	while ( it != end )
	{
		it->pSpinControl->SetRange( static_cast<float>( roundNumber( it->nPixelMin * nPixelToUnitFactor_, 2 ) ),
									static_cast<float>( roundNumber( it->nPixelMax * nPixelToUnitFactor_, 2 ) ) );
		it->pSpinControl->SetDelta( nDelta );

		++it;
	}
}


EUNIT CSpinUnits::getCurrentUnit() const
{
	return CurrentUnit_;
}

double CSpinUnits::roundNumber( double dVal, int iDigits )
{
	int iFactor = 1;
	while ( iDigits-- > 0 )
	{
		iFactor *= 10;
	}
	dVal *= iFactor;
	dVal = (int)dVal;
	dVal /= iFactor;

	return dVal;
}

void CSpinUnits::getFormattedCoordinate( OUT CString &str, IN int nPixel )
{
	if ( nPixelToUnitFactor_ == 1 )
	{
		str.Format( _T("%d"), nPixel );
	} else {
		str.Format( _T("%0.2f"), nPixelToUnitFactor_ * nPixel );
	}
}
